package com.boful.common.file.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.activation.MimetypesFileTypeMap;

import com.boful.common.file.utils.FileUtils;

public class LocalFileSystem extends FileSystem {

	private String url;
	private File file;

	LocalFileSystem(String url) {
		this.url = url;
		file = new File(url);
	}

	@Override
	public char getSeparator() {
		return File.separatorChar;
	}

	@Override
	public String normalize(String path) {
		return file.toURI().toString();
	}

	@Override
	public String getDefaultParent() {
		// TODO Auto-generated method stub
		return file.getParent();
	}

	@Override
	public boolean isAbsolute() {
		// TODO Auto-generated method stub
		return file.isAbsolute();
	}

	@Override
	public long getLastModifiedTime() {
		// TODO Auto-generated method stub
		return file.lastModified();
	}

	@Override
	public long getLength() {
		// TODO Auto-generated method stub
		return file.length();
	}

	@Override
	public boolean delete() {
		// TODO Auto-generated method stub
		return file.delete();
	}

	@Override
	public String[] list() {
		// TODO Auto-generated method stub
		return file.list();
	}

	@Override
	public NetFile[] listFiles() {
		// TODO Auto-generated method stub
		File[] fies = file.listFiles();
		NetFile[] netFiles = new NetFile[fies.length];
		for (int i = 0; i < netFiles.length; i++) {
			try {
				netFiles[i] = new NetFile(fies[i].getAbsolutePath());
			} catch (Exception e) {
				return null;
			}
		}
		return netFiles;
	}

	@Override
	public boolean createDirectory() {
		return file.mkdirs();
	}

	@Override
	public boolean rename(NetFile f2) {
		if (f2.getScheme().equals("file")) {
			return file.renameTo(new File(f2.getUrl()));
		} else {
			return false;
		}

	}

	@Override
	public String getScheme() {
		return "file";
	}

	@Override
	public InputStream getInputStream() {
		try {
			return new FileInputStream(file);
		} catch (FileNotFoundException e) {
			return null;
		}
	}

	@Override
	public OutputStream getOutputStream() {
		try {
			return new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			return null;
		}
	}

	@Override
	public String getName() {
		return file.getName();
	}

	@Override
	public boolean exist() {
		return file.exists();
	}

	@Override
	public boolean copyTo(NetFile destFile) {

		try {
			FileUtils.copyFile(destFile.getInputStream(),
					destFile.getOutputStream());
			return true;
		} catch (FileNotFoundException e) {
			return false;
		}
	}

	@Override
	public String getContentType() {
		return new MimetypesFileTypeMap().getContentType(file);
	}

	@Override
	public boolean isDirectory() {
		return file.isDirectory();
	}

}
